package com.nsgf.library.ui.mine;

import static android.view.View.GONE;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;

import android.app.Dialog;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.JsonObject;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.kunminx.binding_recyclerview.adapter.SimpleDataBindingAdapter;
import com.nsgf.library.data.api.APIs;
import com.nsgf.library.data.bean.OrderListBean;
import com.nsgf.library.data.bean.PointListBean;
import com.nsgf.library.data.bean.PointListBean.ListBean;
import com.nsgf.library.data.bean.UserDataBean;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.StringUtil;
import com.nsgf.library.utils.ToastUtils;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhht.htzx.BR;
import com.zhht.htzx.R;
import com.zhht.htzx.databinding.ActivityMinePointsBinding;
import com.zhht.htzx.databinding.DialogPointExchangeBinding;
import com.zhht.htzx.databinding.ItemMinePointsDetailsBinding;
import com.zhht.htzx.databinding.ItemMinePointsGoodsBinding;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * 新人专享
 */
public class MinePointsActivity extends BaseActivity {

    private NewComersStates mStates;

    private SimpleDataBindingAdapter<PointListBean.ListBean, ItemMinePointsDetailsBinding> mAdapter;

    private AccountRequester mAccountRequester;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(NewComersStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new SimpleDataBindingAdapter<PointListBean.ListBean, ItemMinePointsDetailsBinding>(this, R.layout.item_mine_points_details,
                new DiffUtil.ItemCallback<PointListBean.ListBean>() {
                    @Override
                    public boolean areItemsTheSame(@NonNull PointListBean.ListBean oldItem, @NonNull PointListBean.ListBean newItem) {
                        return oldItem.getId() == newItem.getId();
                    }

                    @Override
                    public boolean areContentsTheSame(@NonNull PointListBean.ListBean oldItem, @NonNull PointListBean.ListBean newItem) {


                        if (oldItem.getId() != newItem.getId())
                            return false;
                        if (!oldItem.getCreateTime().equals(newItem.getCreateTime()))
                            return false;
                        if (!oldItem.getTitle().equals(newItem.getTitle()))
                            return false;
                        if (!oldItem.getDescription().equals(newItem.getDescription()))
                            return false;
                        if (oldItem.getPoint() != newItem.getPoint())
                            return false;

                        return true;
                    }
                }) {
            @Override
            protected void onBindItem(ItemMinePointsDetailsBinding binding, PointListBean.ListBean item,
                                      RecyclerView.ViewHolder holder) {
                binding.setVm(item);

                if (null != item.getTradeOrderResp()) {
                    SimpleDataBindingAdapter<PointListBean.ListBean.TradeOrderRespBean.ItemsBean
                            , ItemMinePointsGoodsBinding> mAdapterChild =
                            new SimpleDataBindingAdapter<PointListBean.ListBean.TradeOrderRespBean.ItemsBean
                                    , ItemMinePointsGoodsBinding>(MinePointsActivity.this,
                                    R.layout.item_mine_points_goods, new DiffUtil.ItemCallback<ListBean.TradeOrderRespBean.ItemsBean>() {
                                @Override
                                public boolean areItemsTheSame(@NonNull ListBean.TradeOrderRespBean.ItemsBean oldItem,
                                                               @NonNull ListBean.TradeOrderRespBean.ItemsBean newItem) {
                                    return false;
                                }

                                @Override
                                public boolean areContentsTheSame(@NonNull ListBean.TradeOrderRespBean.ItemsBean oldItem,
                                                                  @NonNull ListBean.TradeOrderRespBean.ItemsBean newItem) {
                                    return false;
                                }
                            }) {
                                @Override
                                protected void onBindItem(ItemMinePointsGoodsBinding binding,
                                                          PointListBean.ListBean.TradeOrderRespBean.ItemsBean childItem,
                                                          RecyclerView.ViewHolder holder) {
                                    binding.setVm(childItem);
                                    binding.setVmInfo(item.getTradeOrderResp());
                                }
                            };
                    binding.setAdapterChild(mAdapterChild);
                    binding.recyclerView.setVisibility(VISIBLE);
                    mAdapterChild.submitList(item.getTradeOrderResp().getItems());

                } else {
                    binding.recyclerView.setVisibility(GONE);
                }
            }
        };
        return new DataBindingConfig(R.layout.activity_mine_points, BR.vm, mStates)
                .addBindingParam(BR.click, new ClickProxy())
                .addBindingParam(BR.adapter, mAdapter);
    }

    private ActivityMinePointsBinding mBinding;

    private int type = 0;
    private UserDataBean userDataBeanState;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);
        mBinding = (ActivityMinePointsBinding) getBinding();
        mStates.titleBar.set(getIntent().getStringExtra("title"));
        type = getIntent().getIntExtra("index", 0);
        userDataBeanState = getIntent().getParcelableExtra("data");
        mAccountRequester.getPointDetail();


        for (UserDataBean.UserBean.SysConfigListBean sysConfigListBean : userDataBeanState.getSysConfigList()) {

            if (APIs.transfer_of_benefit_points_features.equals(sysConfigListBean.getConfigKey())) {
                if ("1".equals(sysConfigListBean.getConfigValue())) {
                    mBinding.llPointsExchange.setVisibility(VISIBLE);
                } else {
                    mBinding.llPointsExchange.setVisibility(INVISIBLE);
                }
            }

        }
        mAccountRequester.getSrcSuccess().observe(this, new Observer<ResponseStatus<String>>() {
            @Override
            public void onChanged(ResponseStatus<String> stringResponseStatus) {
                if (stringResponseStatus.getResponseCode() == 0) {
                    ToastUtils.showShortToast(stringResponseStatus.getMsg());
                    mAccountRequester.getPointDetail();
                }
            }
        });
        mAccountRequester.getUserResultProject().observe(this, new Observer<ResponseStatus<UserDataBean>>() {
            @Override
            public void onChanged(ResponseStatus<UserDataBean> response) {
                if (response.getResponseCode() == 0) {
                    mStates.userDataBeanState.set(response.getData());
                }
            }
        });

        mAccountRequester.getPointBeanResult().observe(this, new Observer<ResponseStatus<PointListBean>>() {
            @Override
            public void onChanged(ResponseStatus<PointListBean> response) {
                if (response.getResponseCode() == 0) {

                    if (page == 1) {
                        mBinding.swipeRefreshLayout.finishRefresh();
                        mStates.pointsList.set(response.getData().getList());
                        if (!mStates.pointsList.get().isEmpty())
                            mBinding.ivListNotData.setVisibility(GONE);
                        else mBinding.ivListNotData.setVisibility(VISIBLE);
                    } else {
                        mBinding.swipeRefreshLayout.finishLoadMore();

                        List<PointListBean.ListBean> currentList = mStates.pointsList.get();
                        if (currentList != null) {
                            currentList.addAll(response.getData().getList());
                            mStates.pointsList.set(currentList);
                        }
                    }
                }
            }
        });

        mAccountRequester.getStringResult().observe(this, new Observer<ResponseStatus<Object>>() {
            @Override
            public void onChanged(ResponseStatus<Object> objectResponseStatus) {
                if (objectResponseStatus.getResponseCode() == 0) {

                    mStates.pointRate.set(objectResponseStatus.getData().toString() + "+1个惠通宝");
                    if (null == dialog) {

                        dialog = new Dialog(MinePointsActivity.this);
                        View view = View.inflate(MinePointsActivity.this, R.layout.dialog_point_exchange, null);
                        DialogPointExchangeBinding exchangeBinding = DataBindingUtil.bind(view);
                        exchangeBinding.setVm(mStates);
                        exchangeBinding.setClick(new ClickProxy());
                        dialog.setContentView(view);
                    }

                    Window window = dialog.getWindow();
                    window.setBackgroundDrawableResource(android.R.color.transparent);
                    WindowManager.LayoutParams lp = window.getAttributes();
                    lp.width = getResources().getDisplayMetrics().widthPixels;
                    window.setAttributes(lp);
                    window.setGravity(Gravity.BOTTOM); // 此处可以设置dialog显示的位置
                    dialog.show();
                }
            }
        });

        mBinding.swipeRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getDatas();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getDatas();
            }
        });

        mBinding.swipeRefreshLayout.autoRefresh();
    }

    private void getDatas() {
        mAccountRequester.getPointsBenefit(page, 0);
    }

    private int page = 1;


    public static class NewComersStates extends StateHolder {

        public final State<List<PointListBean.ListBean>> pointsList = new State<>(new ArrayList<>());
        public final State<UserDataBean> userDataBeanState = new State<>(new UserDataBean());


        public final State<String> pointNumber = new State<>("");//转让积分

        public final State<String> userId = new State<>("");//转让目标id
        public final State<String> pointRate = new State<>("");//积分费率
    }

    private Dialog dialog;

    public class ClickProxy {
        public void exchangePoint() {

            if (null == dialog) {

                mAccountRequester.getWelfarePoints();

            } else
                dialog.show();
        }

        public void submitExchangePoint() {

            if (StringUtil.isEmpty(mStates.pointNumber.get()) ||
                    StringUtil.isEmpty(mStates.userId.get())) {
                ToastUtils.showShortToast("请正确输入转让信息");
                return;
            }

            if (null != dialog) {
                dialog.dismiss();
            }
            JsonObject params = new JsonObject();
                params.addProperty("welfarePoint", mStates.pointNumber.get());
                params.addProperty("userId", mStates.userId.get());
                mAccountRequester.welfarePointsTransfer(params);

        }
    }


}
